package com.tensquare.test.spit.service;

import com.tensquare.test.spit.dao.SpitDao;
import com.tensquare.test.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import util.IdWorker;

import java.util.Date;
import java.util.List;

@Transactional
@Service
@CrossOrigin
public class SpitService {
    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    public void thumbup(String id) {
        Spit spit = spitDao.findById(id).get();
        spit.setThumbup(spit.getThumbup() == null ? 1 : spit.getThumbup() + 1);
        spitDao.save(spit);

     /*   //拼装mongdb语句。db.spit.updata({"_id":"1"},{$inc:{thumbup:NumberInt(1)}})
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is("1"));
        Update update = new Update();
        update.inc("thumbup",1);
        mongoTemplate.updateFirst(query,update,"spit");*/
    }

    public List<Spit> findAll() {
        return spitDao.findAll();
    }

    public Page<Spit> findByParentId(String id, int size, int page) {

        Pageable pageable = PageRequest.of(page - 1, size);
        return spitDao.findByParentid(id, pageable);


    }

    public Spit findById(String id) {
        return spitDao.findById(id).get();
    }

    public void updata(Spit spit) {
        spitDao.save(spit);

    }

    public void save(Spit spit) {
        spit.set_id(idWorker.nextId() + "");
        spit.setPublishtime(new Date());
        spit.setVisits(0);
        spit.setShare(0);
        spit.setThumbup(0);
        spit.setComment(0);
        spit.setState("1");

        //如果当前添加的节点有父节点，那么父节点的评论数加1
        if (spit.getParentid()!=null&&"".equals(spit.getParentid())){
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));
            Update update = new Update();
            update.inc("comment",1);
            mongoTemplate.updateFirst(query,update,"spit");
        }

        spitDao.save(spit);
    }

    public void delete(String id) {
        spitDao.deleteById(id);
    }
}
